package com.rybbaby.tss.front.tssPackage.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.consts.RoleConsts;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.AjaxJsonResponse;
import com.rybbaby.tss.core.utils.PropertiesReadUtil;
import com.rybbaby.tss.core.utils.SequenceUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.front.tssPackage.entity.TssPackage;
import com.rybbaby.tss.front.tssPackage.service.ITssPackageService;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @description 课时包表管理
 * 
 * @author 雷春琼
 * 
 * @createDate 2017-08-10 上午12:08:5
 */
@Controller
@RequestMapping(value = "tssPackageController")
public class TssPackageController extends BaseController {
	
	@Autowired
	private ITssPackageService tssPackageService;
	@Autowired
	private ISysAdminUserService sysAdminUserService;
	
	/**
	 * 获取课时包表列表
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestLog(content = "获取课时包表列表" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "tssPackageList" , method = RequestMethod.POST)
	public ModelAndView tssPackageList(TssPackage entity , PageBean paramPageBean,@RequestParam(required = true) Integer type) {
		ModelAndView mav = null;
		try {
			if (type == 1) {
				//亲子课时包设置
				mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssPackageListView"));
			} else if (type == 2) {
				//过渡课时包设置
				mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitPackageListView"));
			}
			Map<String , String []> unLockMap = getParameterMap(request);
			DetachedCriteria dc = DetachedCriteria.forClass(TssPackage.class);
			HqlGenerateUtil.fillDetachedCriteria(dc , entity , unLockMap);
			String ids = "";
			//获取当前登录者
			String adminUserId = super.getLoginUser().getId();

			SysAdminUser sysAdminUser=this.sysAdminUserService.get(adminUserId);
			//获取当前登录者所拥有角色
			List<String> roleList = super.getLoginAdminRoles();

			if(roleList.contains(RoleConsts.TSS_COUNSELOR)||roleList.contains(RoleConsts.TSS_TEACHER)){
				dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + adminUserId + "') "));
			} else{
				List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
				ids = StringUtils.join(idsList, "','");
				dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
			}
			dc.add(Restrictions.eq("type",type));
			dc.addOrder(Order.desc("updateTime"));
			PageBean pageBean = tssPackageService.pageList(dc , paramPageBean.getPageNo() , paramPageBean.getPageSize());
			mav.addObject(super.SEARCH_MAP , unLockMap);
			mav.addObject(super.PAGE_BEAN , pageBean);
			mav.addObject("searchFormId" , SEARCH_FORM);
			mav.addObject("actionUrl" , request.getRequestURI());
			mav.addObject("pagingBar" , pageBean.getPagingBar(SEARCH_FORM));
			mav.addObject("serializeNum" , SequenceUtil.getUpperCaseUUID());
			String requestURI = StringUtils.substringBeforeLast(request.getRequestURI() , "/");
			mav.addObject("editUrl" , requestURI + "/toEditView.do");
			mav.addObject("deleteUrl" , requestURI + "/delete.do");
			mav.addObject("batchDeleteUrl" , requestURI + "/batchDelete.do");
		} catch (Exception e) {
			throw e;
		}
		return mav;
	}
	/**根据类型异步加载课程包
	 *
	 *
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "根据类型异步加载课程包" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "ajaxPackageListByType",method = RequestMethod.GET)
	public String ajaxPackageListByType(@RequestParam(required = true) String type) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			DetachedCriteria dc = DetachedCriteria.forClass(TssPackage.class);
			//dc.add(Restrictions.eq("type", type));
			//List<TssPackage> data =this.tssPackageService.findByDetached(dc);
			String sql ="select * from tss_package where type = "+type;
			List<TssPackage> data = this.tssPackageService.findListBySql(sql);

			ajr.setData(data.toArray());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ajr.jsonResponse(true);
	}
	/**
	 * 转到编辑视图
	 * 
	 * @param targetDateId
	 *            接收编辑参数的临时对象
	 * @param serializeNum
	 *            请求标识
	 * @return
	 */
	@RequestLog(content = "转到课时包表视图" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "toEditView" , method = RequestMethod.GET)
	public ModelAndView toEditView(@RequestParam(required = true) String targetDateId, @RequestParam(required = true) String serializeNum,@RequestParam(required = true) String packageType) {
		ModelAndView mav =null;
		Integer type=Integer.valueOf(packageType);
		if(type==1){
			mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssPackageEditView"));
		}else if(type==2){
			mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitPackageEditView"));
		}
		if(StringUtils.isNotBlank(targetDateId)) {
			TssPackage editEntity = this.tssPackageService.get(targetDateId);
			mav.addObject("editEntity" , editEntity);
			mav.addObject("editModel" , "edit");
		}else{
			mav.addObject("editModel" , "add");
		}
		mav.addObject("serializeNum" , serializeNum);
		mav.addObject("saveUrl" , StringUtils.substringBeforeLast(request.getRequestURI() , "/") + "/saveOrUpdate.do");
		return mav;
	}
	
	/**
	 * 保存编辑的对象
	 * 
	 * @param entity
	 *            被编辑对象
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "保存课时包表对象" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "saveOrUpdate" , method = RequestMethod.POST)
	public String saveOrUpdate(TssPackage entity) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			String id=entity.getId();
			ajr.setResMsg("保存成功!");
			if(StringUtils.isNotBlank(id)){
				TssPackage destEntity = this.tssPackageService.get(id);
				entity.setAdminUserId(super.getLoginUser().getId());
				BeanUtils.copyProperties(entity , destEntity ,"createTime","updateTime");
				destEntity.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
				this.tssPackageService.updateEntitiy(destEntity);
			} else {
				entity.setAdminUserId(super.getLoginUser().getId());
				entity.setIsBlockUp(true);
				entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
				Serializable newId = this.tssPackageService.save(entity);
				if(newId == null) {
					ajr.setResCode(301);
					ajr.setResMsg("保存失败!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}
	
	/**
	 * 删除指定id的对象
	 * 
	 * @param id
	 *            需要被删除的对象id
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "删除属性" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "delete" , method = RequestMethod.GET)
	public String delete(@StringValidator(nullable = false) String id) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			ajr.setResMsg("删除成功!");
			if(StringUtils.isNotBlank(id)) {
				this.tssPackageService.deleteEntityById(id);
			} else {
				ajr.setResMsg("删除失败!");
				ajr.setResCode(302);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}
	
	/**
	 * 批量删除指定id的对象
	 * 
	 * @param ids
	 *            需要被删除的对象id组成的字符串
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "删除属性" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "batchDelete" , method = RequestMethod.GET)
	public String batchDelete(@RegexpValidator(nullable = false , regexp = "^(\\w+,?)+\\w+$") String ids) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			ajr.setResMsg("删除成功!");
			if(StringUtils.isNotBlank(ids)) {
				boolean batchDelete = this.tssPackageService.batchDelete(ids.split(","));
				if(!batchDelete) {
					ajr.setResMsg("删除失败!");
					ajr.setResCode(302);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}

	/**
	 * 根据状态修改课时包信息
	 * @param targetDateId
	 * @param isBlockUp
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "根据状态修改课时包信息", save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "updatePackageByIsBlockUp", method = RequestMethod.POST)
	public String updatePackageByIsBlockUp(@RequestParam(required = true) String targetDateId, @RequestParam(required = true) Boolean isBlockUp) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			Integer status = this.tssPackageService.updatePackageByIsBlockUp(targetDateId, isBlockUp);
			if (status == null) {
				ajr.setResMsg("修改失败!");
				ajr.setResCode(302);
			}else{
				ajr.setResMsg("修改成功!");
				ajr.setResCode(200);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("修改失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(true);

	}


	/**
	 * 验证同园课时包名不可重复
	 *
	 * @param name 课时包
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "验证同园课时包名不可重复", save = true)
	@RequestMapping(value = "verificationPackageName", method = RequestMethod.POST)
	public String verificationPackageName(String name,String id) {
		try {
			String sqll=super.getLoginUser().getSchoolId();
			StringBuffer sql = new StringBuffer();
			sql.append(" SELECT COUNT(1) count from tss_package tp left join sys_admin_user sau on sau.id=tp.adminUserId  \n" +
					"where sau.schoolId=? and tp.`name`=?");
			if (id != null && id != "") {
				sql.append(" AND tp.id != '" + id + "'");
			}
			Map<String, Object> findOneForJdbc = sysAdminUserService.findOneForJdbc(sql.toString(), new Object[]{super.getLoginUser().getSchoolId(),name});
			return responseRemoteValidate(findOneForJdbc != null && !findOneForJdbc.isEmpty() && findOneForJdbc.containsKey("count") && (findOneForJdbc.get("count").toString()).equals("0"));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
